import type { RouteRecordRaw } from 'vue-router'

export function mapMenusToRouters(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []

  const allRoutes: RouteRecordRaw[] = []
  const routeFiles = require.context('../router/main', true, /\.ts/)
  routeFiles.keys().forEach((key) => {
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const route = require('../router/main' + key.split('.')[1])
    allRoutes.push(route.default)
  })

  const _recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type == 2) {
        const route = allRoutes.find((route) => {
          return route.path === menu.url
        })
        if (route) routes.push(route)
      } else {
        if (menu.children) _recurseGetRoute(menu.children)
      }
    }
  }
  _recurseGetRoute(userMenus)
  return routes
}

export function pathMapBreadcrumbs(userMenus: any[], path: string): any[] {
  const breadcrumbs: any[] = []
  const _recurseGetBreadcrumbs = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type == 2) {
        if (menu.url === path) {
          breadcrumbs.push(menu)
          return true
        }
      } else {
        if (menu.children) {
          const result = _recurseGetBreadcrumbs(menu.children)
          if (result) {
            breadcrumbs.unshift(menu)
            return breadcrumbs
          }
        }
      }
    }
  }
  _recurseGetBreadcrumbs(userMenus)
  return breadcrumbs
}
